#include "console.h"
#include <sys/types.h>
#include <sys/time.h>
#include <time.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

/*************************** Date/Time Setup **************************/
static int str2tm(const char * str, struct tm * tp)
{
        int i, k = 0;
        char dt[20];

        if (strlen(str) != 14) return -1;
        for (i = 0; i < 14; i++) {
                if (!isdigit(*(str + i))) return -1;
                dt[k ++] = *(str + i);
                if (k >= 4 && (k % 3 == 1)) {
                        dt [k ++] = 0;
                }
        }

        tp->tm_year = strtoul(dt, (char **)0, 10) - 1900;
        tp->tm_mon = strtoul(dt + 5, (char **)0, 10) - 1;
        tp->tm_mday = strtoul(dt + 8, (char **)0, 10);
        tp->tm_hour = strtoul(dt + 11, (char **)0, 10);
        tp->tm_min = strtoul(dt + 14, (char **)0, 10);
        tp->tm_sec = strtoul(dt + 17, (char **)0, 10);
        return 0;
}

static void date_help(void)
{
        printf("Usage: \n\tdate [YYYYMMDDHHMMSS]\n");
        printf("Example:\n\tdate 20121221235959\n");
}

void command_date(int argc, const char **argv)
{
        time_t tv;
        struct tm t;
        if (argc == 1) {
                char tstr[48];
                time(&tv);
                localtime_r(&tv, &t);
                asctime_r(&t, tstr);
                printf("\t%s", tstr);
        }
        else if (argc == 2) {
                 if (strncmp(argv[1], "help", 4) == 0) {
                        date_help();
                        return;
                 }
                struct timeval val;
                if (str2tm(argv[1], &t) < 0) {
                        printf("Invalid date\n");
                        return;
                }
                tv = mktime(&t);
                val.tv_sec = tv;
                val.tv_usec = 0;
                settimeofday(&val, NULL);
        }
        return;
}

const command_t date_cmd __command_entry = {
        "date",
        command_date,
        "date -- Show & Change the current date/time"
};
